package com.paddyi.config;

import com.paddyi.commons.http.HttpResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @program: paddyi
 * @description: GlobalExceptionController
 * @author: paddy
 * @create: 2019-06-13 18:14
 **/
@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class GlobalExceptionController extends AbstractErrorController {
    private final static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionController.class);

    private final ErrorProperties errorProperties;
    @Autowired
    public GlobalExceptionController(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
        super(errorAttributes);
        this.errorProperties=serverProperties.getError();
    }
    @Override
    public String getErrorPath() {
        return errorProperties.getPath();
    }

    @RequestMapping(produces = "text/html")
    public ModelAndView errorHtml(HttpServletRequest request,
                                  HttpServletResponse response) {
        ModelAndView modelAndView=new ModelAndView("error");
        Map<String, Object> errorMap=getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
        if(errorMap!=null) {
            /*timestamp status error message path*/
            modelAndView.addObject("msg",errorMap.get("error"));
            modelAndView.addObject("statusCode",errorMap.get("status"));
            logHandler(errorMap);
        }
        return modelAndView;
    }

    @RequestMapping
    @ResponseBody
    public HttpResult error(HttpServletRequest request) {
        Map<String, Object> errorMap = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.APPLICATION_JSON));
        logHandler(errorMap);
        int code  = (int) errorMap.get("status");
        LOGGER.error("程序异常，错误代码:"+code);
        switch (code){
            case 401:
                return HttpResult.error(code,"未登录:");
            case 403:
                return HttpResult.error(code,"未取得权限:");
        }

        return HttpResult.error("未知错误:");
    }

    //日志记录到这里
    private void logHandler(Map<String, Object> errorMap) {
//        log.error("url:{},status{},time:{},errorMsg:{}",errorMap.get("path"),errorMap.get("status"),errorMap.get("timestamp"),errorMap.get("message"));
    }

    protected boolean isIncludeStackTrace(HttpServletRequest request,
                                          MediaType produces) {
        ErrorProperties.IncludeStacktrace include = getErrorProperties().getIncludeStacktrace();
        if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
            return true;
        }
        if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM) {
            return getTraceParameter(request);
        }
        return false;
    }
    private ErrorProperties getErrorProperties() {
        return this.errorProperties;
    }
}
